package com.example.qa_back.utils;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 董帅
 * @date 2021/4/9 - 15:29
 */
public class ConnectPython {
    public static ArrayList<Double> execPython(String str) {
        byte[] bytes = str.getBytes(StandardCharsets.UTF_8);
        String ip = "localhost";
        int port = 8094;
        Socket socket = null;
        ArrayList<Double> list = new ArrayList<>();
        try {
            // 连接python服务器
            socket = new Socket(ip, port);
            // 获取输入流
            InputStream in = socket.getInputStream(); // 读取数据
            //获取输出流，向服务器端发送信息
            OutputStream out = socket.getOutputStream();// 发送数据
            // 包装输入流，输出流，包装一下可以直接传输字符串
            // 不包装的话直接使用InputStream和OutputStream只能直接传输byte[]类型数据
            BufferedReader inRead = new BufferedReader(new InputStreamReader(in));
            out.write(bytes);
            // 使用了包装后的输入流方便读取消息
            String result = inRead.readLine();
            System.out.println(result);
            if (result != null) {
                String[] split = result.split(" ");
                for (String s : split) {
                    list.add(Double.valueOf(s));
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }

    public static List<Double> execPythonDP(String str) {
        byte[] bytes = str.getBytes(StandardCharsets.UTF_8);
        String ip = "localhost";
        int port = 8095;
        Socket socket = null;
        ArrayList<Double> list = new ArrayList<>();
        try {
            socket = new Socket(ip, port);
            InputStream in = socket.getInputStream();
            OutputStream out = socket.getOutputStream();
            BufferedReader inRead = new BufferedReader(new InputStreamReader(in));
            out.write(bytes);
            String result = inRead.readLine();
            System.out.println(result);
            String[] split = result.split(" ");
            for (String s : split) {
                list.add(Double.valueOf(s));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }
}
